import collections
import datetime
import json
import sys
# from datetime import datetime

import psutil

# print(sys.path)

disk_used = collections.OrderedDict()
arrayList = ' '
def getMemCpu():
    global arrayList
    data = psutil.virtual_memory()
    total = data.total  # 总内存,单位为byte
    # print('total', total)

    totalN = bytes2human(total);
    arrayList = totalN
    print('运行内存', totalN)

    free = bytes2human(data.available)  # 可用内存
    print('剩余运行内存', free)
    arrayList =arrayList + ',' +free

    memory = "%d" % (int(round(data.percent))) + "%" + " "  # 运行内存使用情况
    arrayList =arrayList + ',' +memory
    print('内存使用情况', memory)
    cpu = "%0.2f" % psutil.cpu_percent(interval=1) + "%"  # CPU占用情况
    arrayList =arrayList + ',' +cpu
    print('cpu占用情况', cpu)

    cpuWuli = psutil.cpu_count(logical=False);
    arrayList =arrayList + ',' + str(cpuWuli)
    print('cpu物理个数', cpuWuli)

    psutil.boot_time()  # 以linux时间格式返回

    beginTime =  datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H: %M: %S")  # 转换成自然时间格式
    arrayList =arrayList + ',' +beginTime
    print('开机时间', beginTime)

def bytes2human(n):
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%0.2f%s' % (value,s)
    return '%sB' % n

def get_disk_info():
    """
    查看磁盘属性信息
    :return: 磁盘使用率和剩余空间
    """
    for id in psutil.disk_partitions():
        if 'cdrom' in id.opts or id.fstype == '':
            continue
        disk_name = id.device.split(':')
        s = disk_name[0]
        disk_info = psutil.disk_usage(id.device)
        disk_used[s + '盘使用率：'] = '{}%'.format(disk_info.percent)
        disk_used[s + '剩余空间：'] = '{}GB'.format(disk_info.free // 1024 // 1024 // 1024)
    return disk_used

if __name__ == "__main__":
    getMemCpu()
    row = get_disk_info();
    for cipan in row:
        print(cipan,row[cipan])
        arrayList =arrayList + ',' +row[cipan]
    # print('磁盘信息', row['C盘使用率：'])
    json_str = json.dumps(arrayList)
    print(json_str)